package com.lagou.edu.listener;

import com.lagou.edu.annotation.PackageScan;
import com.lagou.edu.factory.AnnotationBeanFactory;
import com.lagou.edu.utils.BeanFactoryUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.reflect.InvocationTargetException;

public class IoCListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String configClassName = servletContextEvent.getServletContext().getInitParameter("IoCConfig");
        try {
            Class<?> configClass = Class.forName(configClassName);
            PackageScan packageScan = configClass.getAnnotation(PackageScan.class);
            if (packageScan != null) {
                String[] packages = packageScan.value();
                AnnotationBeanFactory annotationBeanFactory = createAnnotationBeanFactory(packages);
                BeanFactoryUtils.setFactory(annotationBeanFactory);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {}

    private AnnotationBeanFactory createAnnotationBeanFactory(String... packages) {
        AnnotationBeanFactory annotationBeanFactory = new AnnotationBeanFactory();
        annotationBeanFactory.loadBeans(packages);
        return annotationBeanFactory;
    }
}
